import {
  getCoverageStats,
  getLicenseInfo,
  getReportURL,
  getSummary,
  parseSarif,
  QODANA_CHECK_NAME
} from '../../common/output'
import {
  getCoverageFromSarif,
  QODANA_SARIF_NAME,
  QODANA_SHORT_SARIF_NAME,
  VERSION
} from '../../common/qodana'
import {getWorkflowRunUrl, postResultsToPRComments} from './utils'

export const DEPENDENCY_CHARS_LIMIT = 65336 // 65,336 chars is the GitLab limit for a comment
export const VIEW_REPORT_OPTIONS = `To be able to view the detailed Qodana report, you can either:
  - Register at [Qodana Cloud](https://qodana.cloud/) and [configure the pipeline](https://www.jetbrains.com/help/qodana/gitlab.html#Expose+Qodana+reports)
  - Inspect and use \`qodana.sarif.json\` (see [the Qodana SARIF format](https://www.jetbrains.com/help/qodana/qodana-sarif-output.html#Report+structure) for details)

To get \`*.log\` files or any other Qodana artifacts, run the task with \`upload-result\` option set to \`true\`, 
so that the job will upload the files as the job artifacts:

\`\`\`yaml
        include:
          - component: $CI_SERVER_FQDN/qodana/qodana/qodana-gitlab-ci@${VERSION}
            inputs:
              upload-result: true
\`\`\`
`

export function getQodanaHelpString(): string {
  return `This result was published with [Qodana](<${getWorkflowRunUrl()}>)`
}

export async function publishOutput(
  projectDir: string,
  sourceDir: string,
  resultsDir: string,
  postComment: boolean,
  isPrMode: boolean,
  execute: boolean
): Promise<void> {
  if (!execute) {
    return
  }
  try {
    const problems = parseSarif(
      `${resultsDir}/${QODANA_SARIF_NAME}`,
      getQodanaHelpString()
    )
    const reportUrl = getReportURL(resultsDir)
    const coverageInfo = getCoverageStats(
      getCoverageFromSarif(`${resultsDir}/${QODANA_SHORT_SARIF_NAME}`),
      true
    )

    const licensesInfo = getLicenseInfo(resultsDir)

    const problemsDescriptions = problems.problemDescriptions ?? []
    const toolName = problems.title.split('found by ')[1] ?? QODANA_CHECK_NAME
    problems.summary = getSummary(
      toolName,
      projectDir,
      sourceDir,
      problemsDescriptions,
      coverageInfo,
      licensesInfo.packages,
      licensesInfo.licenses,
      reportUrl,
      isPrMode,
      DEPENDENCY_CHARS_LIMIT,
      VIEW_REPORT_OPTIONS
    )
    if (postComment) {
      await postResultsToPRComments(
        toolName,
        sourceDir,
        problems.summary,
        problemsDescriptions.length != 0,
        postComment
      )
    }
  } catch (e) {
    console.error((e as Error).message)
  }
}

/*
 * The pull request with quick-fixes body template.
 */
export function prFixesBody(jobUrl: string): string {
  return ` 🖐 Hey there!

This pull request has been auto-generated by the [Qodana Scan pipeline](<${jobUrl}>) configured in your repository.
It has performed code analysis and applied some suggested fixes to improve your code quality 🧹✨

> **Warning**
>  It's crucial to review these changes to ensure everything shipshape manually. Please take a moment to examine the changes here. Remember to run your integration tests against this PR to validate the fixes and ensure everything's functioning as expected.

_💻🔍 Happy reviewing and testing!
Best,
[Qodana Scan 🤖](https://gitlab.com/qodana/qodana)_`
}
